package com.poisonh.unifiedauth.utils;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.File;

/**
 * Uri 文件路径相关工具类
 * Created by 飘凌雪 on 2016/5/3.
 */
public class UriUtil {


    public static String getPath(Context context, Uri uri) {
        String path = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                if (isExternalStorageDocument(uri)) {
                    String documentId = DocumentsContract.getDocumentId(uri);
                    String[] split = documentId.split(":");
                    if (split.length > 1 && "primary".equalsIgnoreCase(split[0])) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                } else if (isDownloadsDocument(uri)) {
                    String documentId = DocumentsContract.getDocumentId(uri);
                    uri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                    return getPath(context, uri, null, null);
                } else if (isMediaDocument(uri)) {
                    String documentId = DocumentsContract.getDocumentId(uri);
                    String[] split = documentId.split(":");
                    String type = split[0];
                    if ("image".equals(type)) {
                        uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    String selection = "_id=?";
                    String[] selectionArgs = new String[]{split[1]};
                    return getPath(context, uri, selection, selectionArgs);
                } else {
                    return getPath(context, uri, null, null);
                }
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            } else {
                return getPath(context, uri, null, null);
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return path;
    }


    private static String getPath(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        try {
            String[] projection = new String[]{"_data"};
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow("_data");
                return cursor.getString(index);
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 根据文件Uri获取文件名
     *
     * @param uri
     * @return
     */
    public static String getFileName(Uri uri) {
        String fileName = uri.getLastPathSegment();
        if (fileName != null) {
            if (!fileName.contains(".")) {
                fileName = fileName + ".png";
            }
        }
        return fileName;
    }


    /**
     * 根据文件名在bitmap目录下创建文件并返回文件路径
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getBitmapFilePath(Context context, String fileName) {
        File file = context.getExternalFilesDir("bitmap");
        file = new File(file, fileName);
        return file.getAbsolutePath();
    }

    /**
     * 根据文件URi在bitmap目录下创建文件并返回文件路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getBitmapFilePath(Context context, Uri uri) {
        String fileName = getFileName(uri);
        return getBitmapFilePath(context, fileName);
    }

    /**
     * 检测新文件名是否合法，如果已经存在就在后面添加序号以区分
     *
     * @param filePath
     * @return
     */
    public static String checkNewFilePath(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            int index = filePath.lastIndexOf(".");
            String fileName = filePath.substring(0, index);
            String type = filePath.substring(index);
            if (fileName.endsWith(")")) {
                int temp = 0;
                try {
                    temp = Integer.parseInt(String.valueOf(fileName.charAt(fileName.length() - 2)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (temp < 1 || temp > 9) {
                    filePath = fileName + "(1)" + type;
                    return checkNewFilePath(filePath);
                } else {
                    fileName = fileName.substring(0, fileName.length() - 2);
                    filePath = fileName + (temp + 1) + ")" + type;
                    return checkNewFilePath(filePath);
                }
            } else {
                filePath = fileName + "(1)" + type;
                return checkNewFilePath(filePath);
            }
        }
        return file.getAbsolutePath();
    }
}
